import axios from 'axios';
import config from '../config';

const ajaxObject = {};

ajaxObject.axiosInstance = axios.create({
  baseURL: config.ajaxApi,
  timeout: 30000
});

function handleResponse(response) {
  if (response.status !== 200) {
    return { status: response.status, message: response.statusText };
  }

  return response;
};

function handleCatch(error) {
  if (!error.response) {
    return { status: -1, message: error.message };
  }

  return { status: error.response.status, message: error.response.statusText };
};

ajaxObject.get = function(url) {
  return ajaxObject.axiosInstance.get(url).then(handleResponse).catch(handleCatch);
};

ajaxObject.post = function(url, param = {}) {
  return ajaxObject.axiosInstance.post(url, param).then(handleResponse).catch(handleCatch);
};

ajaxObject.put = function(url, param = {}) {
  return ajaxObject.axiosInstance.put(url, param).then(handleResponse).catch(handleCatch);
};

ajaxObject.delete = function(url) {
  return ajaxObject.axiosInstance.delete(url).then(handleResponse).catch(handleCatch);
};

export default ajaxObject;
